package server;

import java.util.InputMismatchException;

import datastructure.Command;

/**
 * A class which manage the commands.
 * 
 * @author dt08sj7
 * 
 */
public class CommandHandler {
	/**
	 * The command to be managed.
	 */
	private Command cmd;
	/**
	 * The security layer of the server.
	 */
	private final SecurityLayer secLayer;

	/**
	 * Creates a new command handler which is connected to the database via the
	 * security layer.
	 * 
	 * @param username
	 *            the username to the database.
	 * @param password
	 *            the password to the database.
	 * @param url
	 *            the url to the database.
	 */
	public CommandHandler(String username, String password, String url) {
		secLayer = new SecurityLayer(username, password, url);
	}

	/**
	 * Creates a new command from a string and add it to the command handler.
	 * 
	 * @param command
	 *            the string to parse the command from.
	 * @return
	 */
	public String newCommand(String command) {
		try {
			cmd = new Command(command);
		} catch (InputMismatchException e) {
			System.out.println("Ogiltigt Format");
			return "NACK";
		} catch (Exception e) {
			System.out.println("Annat Ogiltigt Format...");
			e.printStackTrace();
		}

		System.out.println("Commandhandler newCommand");
		return executeCommand();
	}

	/**
	 * Executes the command by calling the security layer depending on the
	 * command type
	 * 
	 * 
	 * @return a string with the response from the security layer.
	 */

	public String executeCommand() {
		if (cmd.getType().equals("nouncereq")) {
			return secLayer.getNewNounce(cmd.getSsn(), cmd.getHash(), cmd
					.getTimeStamp());

		} else if (cmd.getType().equals("read")) {
			System.out.println("Executing command read");
			return secLayer.readRecords(cmd.getSsn(), cmd.getHash(), cmd
					.logString(), cmd.getTimeStamp(), cmd.getNounce());

		} else if (cmd.getType().equals("append")) {
			return secLayer.appendRecord(cmd.getSsn(), cmd.getHash(), cmd
					.logString(), cmd.getData(), cmd.getTimeStamp(), cmd
					.getNounce());

		} else if (cmd.getType().equals("delete")) {
			return secLayer.deleteRecord(cmd.getSsn(), cmd.getHash(), cmd
					.logString(), cmd.getData(), cmd.getTimeStamp(), cmd
					.getNounce());

		} else if (cmd.getType().equals("deleteall")) {
			return secLayer.deleteAllRecords(cmd.getSsn(), cmd.getHash(), cmd
					.logString(), cmd.getData(), cmd.getTimeStamp(), cmd
					.getNounce());

		} else if (cmd.getType().equals("gethash")) {
			return secLayer.getHash(cmd.getSsn(), cmd.getHash(), cmd
					.logString(), cmd.getTimeStamp(), cmd.getNounce());

		}

		return "NACK";

	}
}
